import esbuild from 'esbuild'
import process from 'process'
import builtins from 'builtin-modules'
import { readFile } from 'fs/promises'

const banner = `/*
${new Date()}
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`

const prod = process.argv[2] === 'production'

const replaceGoober = async (path, encoding) => {
  let contents = await readFile(path, encoding)
  return contents.replace(/_goober/g, 'fileColorPluginGooberStyles')
}

esbuild
  .build({
    banner: {
      js: banner,
    },
    entryPoints: ['src/index.ts'],
    bundle: true,
    external: [
      'obsidian',
      'electron',
      '@codemirror/autocomplete',
      '@codemirror/collab',
      '@codemirror/commands',
      '@codemirror/language',
      '@codemirror/lint',
      '@codemirror/search',
      '@codemirror/state',
      '@codemirror/view',
      '@lezer/common',
      '@lezer/highlight',
      '@lezer/lr',
      ...builtins,
    ],
    format: 'cjs',
    watch: !prod,
    target: 'es2018',
    logLevel: 'info',
    sourcemap: prod ? false : 'inline',
    treeShaking: true,
    outfile: 'main.js',
    plugins: [
      {
        name: 'replacer',
        setup(build) {
          build.onLoad({ filter: /goober/ }, async ({ path }) => {
            return {
              contents: await replaceGoober(path, 'utf-8'),
              loader: 'tsx',
            }
          })
        },
      },
    ],
  })
  .catch(() => process.exit(1))
